package com.sc.web.spring;

import javax.servlet.ServletContext;

import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.openAPI.OpenAPI;
import com.sc.util.spring.SpringUtils;

@Component
public class StartupListener implements ApplicationContextAware,
		ServletContextAware, InitializingBean,
		ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void setApplicationContext(ApplicationContext ctx)
			throws BeansException {
		System.out.println("1 => StartupListener.setApplicationContext");
	}

	@Override
	public void setServletContext(ServletContext context) {
		System.out.println("2 => StartupListener.setServletContext");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("3 => StartupListener.afterPropertiesSet");
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent evt) {
		
		if (evt.getApplicationContext().getParent() == null) {
			
			//登录T+
			OpenAPI api = new OpenAPI(ConfigBeanAdapter.t_srvUrl,ConfigBeanAdapter.t_appKey,ConfigBeanAdapter.t_appSecret,ConfigBeanAdapter.t_user,ConfigBeanAdapter.t_pwd,ConfigBeanAdapter.t_account);
	  		System.out.println("登录！");
	  		api.getTLogin();
	  		
	  		//判断是否要关闭批量上传订单定时器
	  		Scheduler  scheduler = (Scheduler )SpringUtils.getBean("myScheduler");	//批量上传T+订单定时器对象
	  		
			try {  
				 if("false".equals(ConfigBeanAdapter.isEnable_quartz_start)){ //读取配置文件配置标识
			         // scheduler.shutdown();  //关闭定时任务
			          scheduler.deleteJob(JobKey.jobKey("saleOrderBatchInsertDetail"));//删除批量上传T+订单定时器
				 } 
		    } catch (SchedulerException e) {  
		           // TODO Auto-generated catch block  
		           e.printStackTrace();  
		    }  
		}
	}
}